Page({
  data: {
    currentTab: 'minute',
    stockInfo: {},
    stockCode: '',
    stockName: '',
    chartUrl: '',
    buyOrders: [],
    sellOrders: [],
    floatShares: 0, // 流通股本
    turnoverRate: '--', // 换手率
    activeTab: 'trade', // 底部导航当前选中标签
    newsList: [
      {
        title: '渤海汽车：渤海汽车2024年年度报告摘要',
        source: '交易所公告',
        time: '00:07'
      },
      {
        title: '渤海汽车：渤海汽车关于召开2024年度暨2025年第一季度业绩说明会的公告',
        source: '上交所股票',
        time: '00:02'
      },
      {
        title: '图解渤海汽车年报：第四季度单季净利润同比减1066.45%',
        source: '证券之星',
        time: '00:03'
      },
      {
        title: '渤海汽车：渤海汽车关于2024年度计提信用与资产减值准备的公告',
        source: '交易所公告',
        time: '00:01'
      }
    ],
    isFavorite: false, // Add isFavorite state
  },

  onLoad: function(options) {
    console.log('stock-detail onLoad options:', options);
    const code = options.code;
    const name = options.name;
    
    this.setData({
      stockCode: code,
      stockName: name
    });
    
    wx.setNavigationBarTitle({
      title: `${name}(${code})`
    });
    
    // 获取腾讯股票数据(含换手率)
    this.getTencentStockData(code);
    
    // 获取新浪股票数据(买卖盘等详情)
    this.getStockData(code);
    
    // 更新图表URL
    this.updateChartUrl(code);
    
    // 定时刷新数据
    this.dataTimer = setInterval(() => {
      this.getStockData(code);
      this.getTencentStockData(code);
    }, 10000); 
  },
  
  onUnload: function() {
    if (this.dataTimer) {
      clearInterval(this.dataTimer);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('stock-detail onShow');
    // 在 onShow 中检查自选状态
    if (this.data.stockCode) {
      this.checkFavoriteStatus(this.data.stockCode);
    }
  },

  // 获取新浪股票数据
  getStockData: function(code) {
    const prefix = code.startsWith('6') ? 'sh' : 'sz';
    const fullCode = prefix + code;
    
    wx.request({
      url: `https://hq.sinajs.cn/list=${fullCode}`,
      header: {
        'content-type': 'application/json',
        'Referer': 'https://finance.sina.com.cn' 
      },
      success: (res) => {
        console.log('Sina API raw response:', res.data);
        if (res.data) {
          this.parseStockData(res.data);
        }
      },
      fail: (err) => {
        console.error('获取股票数据失败:', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 从腾讯接口获取股票数据(含换手率)
  getTencentStockData: function(code) {
    const prefix = code.startsWith('6') ? 'sh' : 'sz';
    const fullCode = prefix + code;
    
    wx.request({
      url: `https://qt.gtimg.cn/q=${fullCode}`,
      success: (res) => {
        console.log('腾讯数据获取成功');
        if (res.data) {
          try {
            const dataStr = res.data.toString();
            const dataMatch = dataStr.match(/"([^"]+)"/);
            if (dataMatch && dataMatch[1]) {
              const parts = dataMatch[1].split('~');
              
              if (parts.length > 38) {
                const turnover = parts[38];
                console.log('获取到换手率:', turnover);
                
                if (turnover && !isNaN(parseFloat(turnover))) {
                  const turnoverText = parseFloat(turnover).toFixed(2) + '%';
                  
                  this.setData({
                    turnoverRate: turnoverText,
                    'stockInfo.turnover': turnoverText
                  });
                }
                
                // 同时获取流通股本(万股)，在第44位(从0开始)
                if (parts.length > 44) {
                  const floatShares = parseFloat(parts[44]) * 10000;
                  if (floatShares && !isNaN(floatShares) && floatShares > 0) {
                    this.setData({
                      floatShares: floatShares
                    });
                  }
                }
              }
            }
          } catch (error) {
            console.error('解析腾讯股票数据出错:', error);
          }
        }
      },
      fail: (err) => {
        console.error('获取腾讯股票数据失败:', err);
      }
    });
  },
  
        // 格式化数量
        formatVolume: function(num) {
          if (num === undefined || num === null) return '0';
          
          num = parseFloat(num);
          if (isNaN(num)) return '0';
          
          if (num >= 100000000) {
            return (num / 100000000).toFixed(2) + '亿';
          } else if (num >= 10000) {
            return (num / 10000).toFixed(2) + '万';
          } else {
            return num.toFixed(0);
          }
        },
  
  // 解析股票数据
  parseStockData: function(data) {
    console.log('Parsing Sina data:', data);
    try {
      // 从返回的字符串中提取数据部分
      const dataStr = data.split('="')[1].split('";')[0];
      const elements = dataStr.split(',');
      console.log('Parsed elements array:', elements);
      
      // 处理买卖盘数据
      const buyOrders = [
        { price: parseFloat(elements[11]).toFixed(2), volume: this.formatVolume(Math.floor(elements[10]/100)) },
        { price: parseFloat(elements[13]).toFixed(2), volume: this.formatVolume(Math.floor(elements[12]/100)) },
        { price: parseFloat(elements[15]).toFixed(2), volume: this.formatVolume(Math.floor(elements[14]/100)) },
        { price: parseFloat(elements[17]).toFixed(2), volume: this.formatVolume(Math.floor(elements[16]/100)) },
        { price: parseFloat(elements[19]).toFixed(2), volume: this.formatVolume(Math.floor(elements[18]/100)) }
      ];
      
      const sellOrders = [
        { price: parseFloat(elements[21]).toFixed(2), volume: this.formatVolume(Math.floor(elements[20]/100)) },
        { price: parseFloat(elements[23]).toFixed(2), volume: this.formatVolume(Math.floor(elements[22]/100)) },
        { price: parseFloat(elements[25]).toFixed(2), volume: this.formatVolume(Math.floor(elements[24]/100)) },
        { price: parseFloat(elements[27]).toFixed(2), volume: this.formatVolume(Math.floor(elements[26]/100)) },
        { price: parseFloat(elements[29]).toFixed(2), volume: this.formatVolume(Math.floor(elements[28]/100)) }
      ];
      
      // 计算涨跌幅
      const currentPrice = parseFloat(elements[3]);
      const yesterdayClose = parseFloat(elements[2]);
      const priceChange = (currentPrice - yesterdayClose).toFixed(2);
      const changePercent = ((priceChange / yesterdayClose) * 100).toFixed(2);

      // 格式化成交量和成交额
      const volume = parseFloat(elements[8]) / 100; // 转为手
      const amount = parseFloat(elements[9]); // 元
      
      let volumeText = this.formatVolume(volume);
      let amountText = '';
      
      if (amount >= 100000000) {
        amountText = (amount / 100000000).toFixed(2) + '亿';
      } else if (amount >= 10000) {
        amountText = (amount / 10000).toFixed(2) + '万';
      } else {
        amountText = amount.toFixed(2);
      }
      
      // 创建新的stockInfo对象
      const newStockInfo = {
        name: elements[0],
        currentPrice: parseFloat(elements[3]).toFixed(2),
        open: parseFloat(elements[1]).toFixed(2),
        yesterdayClose: parseFloat(elements[2]).toFixed(2),
        high: parseFloat(elements[4]).toFixed(2),
        low: parseFloat(elements[5]).toFixed(2),
        volume: volumeText,
        amount: amountText,
        date: elements[30],
        time: elements[31],
        priceChange: priceChange > 0 ? '+' + priceChange : priceChange,
        changePercent: changePercent > 0 ? '+' + changePercent + '%' : changePercent + '%',
        turnover: this.data.turnoverRate  // 使用从腾讯接口获取的换手率
      };
      
      this.setData({
        stockInfo: newStockInfo,
        buyOrders: buyOrders,
        sellOrders: sellOrders
      });
    } catch (error) {
      console.error('解析股票数据出错:', error);
    }
  },
  
  // 更新图表URL
  updateChartUrl: function(code) {
    const prefix = code.startsWith('6') ? 'sh' : 'sz';
    const fullCode = prefix + code;
    
    let chartUrl = '';
    switch(this.data.currentTab) {
      case 'minute':
        chartUrl = `https://image.sinajs.cn/newchart/min/n/${fullCode}.gif`;
        break;
      case 'day':
        chartUrl = `https://image.sinajs.cn/newchart/daily/n/${fullCode}.gif`;
        break;
      case 'week':
        chartUrl = `https://image.sinajs.cn/newchart/weekly/n/${fullCode}.gif`;
        break;
      case 'month':
        chartUrl = `https://image.sinajs.cn/newchart/monthly/n/${fullCode}.gif`;
        break;
    }
    
    this.setData({
      chartUrl: chartUrl
    });
  },
  // 切换图表类型
  switchTab: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentTab: type
    });
    this.updateChartUrl(this.data.stockCode);
  },

  navigateToNews(e) {
    const news = e.currentTarget.dataset.news;
    wx.navigateTo({
      url: `/pages/news/news?title=${encodeURIComponent(news.title)}&source=${encodeURIComponent(news.source)}&time=${news.time}`
    })
  },
  
  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },
  
  // 切换底部导航
  switchBottomTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    // Only update activeTab for non-favorite tabs if needed
    if (tab !== 'favorite') {
       this.setData({
         activeTab: tab
       });
    }
  },
  
  // 分享功能
  onShareAppMessage: function() {
    return {
      title: `${this.data.stockName}（${this.data.stockCode}）`,
      path: `/pages/stock-detail/index?code=${this.data.stockCode}&name=${this.data.stockName}`,
      success(res) {
        console.log('分享成功', res);
      },
      fail(err) {
        console.error('分享失败', err);
      }
    }
  },

  async checkFavoriteStatus(stockCode) {
    console.log('stock-detail checkFavoriteStatus for code:', stockCode);
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo && userInfo.openid) {
      try {
        const { result } = await wx.cloud.callFunction({
          name: 'user',
          data: {
            type: 'getUserSelectedStocks',
          }
        })

        if (result.success && result.stockCodes.includes(stockCode)) {
          this.setData({
            isFavorite: true
          })
        } else {
          this.setData({
            isFavorite: false
          })
        }
      } catch (error) {
        console.error('检查自选状态失败:', error)
        this.setData({
          isFavorite: false
        })
      }
    } else {
      this.setData({
        isFavorite: false
      })
    }
  },

  async onToggleFavorite() {
    const userInfo = wx.getStorageSync('userInfo')
    const stockCode = this.data.stockCode

    if (!userInfo || !userInfo.openid) {
      // 未登录，跳转到登录页
      wx.navigateTo({
        url: '/pages/login/login',
        events: {
          // 登录成功后返回个股详情页时，重新检查自选状态
          loginSuccess: () => {
            this.checkFavoriteStatus(stockCode)
          }
        }
      })
      return
    }

    // 已登录，调用云函数添加或移除自选
    const type = this.data.isFavorite ? 'removeSelectedStock' : 'addSelectedStock'

    try {
      wx.showLoading({
        title: '操作中...'
      })
      const { result } = await wx.cloud.callFunction({
        name: 'user',
        data: {
          type,
          stockCode
        }
      })
      wx.hideLoading()

      if (result.success) {
        this.setData({
          isFavorite: !this.data.isFavorite // Toggle the state on success
        })
        wx.showToast({
          title: result.message,
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: result.message || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      wx.hideLoading()
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      })
      console.error('自选操作云函数调用失败:', error)
    }
  },
})
